package com.huawei.app.httpapi;

import java.util.Set;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * HTTP API响应结果
 *
 * @since 2021-01-05
 */
public class HttpApiResult {

    public static final int UKNOW_ERROR_CODE = -2;
    public static final int HTTP_ERROR_CODE = -1;

    /**
     * 操作结果码(默认操作成功)
     * 0：失败
     * 1：成功
     */
    protected int retCode = 1;

    /**
     * 操作结果
     */
    protected Object data = null;

    /**
     * 错误描述
     */
    protected String errorMsg = "";

    public HttpApiResult() {
    }

    public static HttpApiResult success() {
        HttpApiResult result = new HttpApiResult();
        result.setRetCode(1);
        return result;
    }

    public static HttpApiResult success(String data) {
        HttpApiResult result = new HttpApiResult();
        result.setRetCode(1);
        result.setData(data);
        return result;
    }

    public static HttpApiResult failed(int retCode, String errorMsg) {
        HttpApiResult result = new HttpApiResult();
        result.setRetCode(retCode);
        result.setErrorMsg(errorMsg);
        return result;
    }

    public boolean isSuccess() {
        return retCode == 1;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("{");
        builder.append("retCode=").append(retCode);
        builder.append(", data=").append(data);
        builder.append(", errorMsg=").append(errorMsg);
        builder.append("}");
        return builder.toString();
    }

    public int getRetCode() {
        return retCode;
    }

    public void setRetCode(int retCode) {
        this.retCode = retCode;
    }

    public Object getRawData() {
        return data;
    }

    public JSONObject getData() {
        Object obj = toJson(data);
        if (obj instanceof JSONObject) {
            return (JSONObject)obj;
        }
        return new JSONObject();
    }

    public void setData(Object data) {
        this.data = data;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    /**
     * 根据点分法查找json对象的属性
     * @param path
     * @return
     */
    public String getValueByPath(String path) {
        JSONObject jsonObj = getData();
        int idx =  path.indexOf(".");
        while (idx != -1) {
            Object tmpObj = jsonObj.get(path.substring(0, idx));
            if (tmpObj instanceof JSONObject) {
                jsonObj = (JSONObject)tmpObj;
                path = path.substring(idx + 1);
                idx =  path.indexOf(".");
                continue;
            }

            jsonObj = null;
            break;
        }
        if (jsonObj == null) {
            return "";
        }
        return String.valueOf(jsonObj.get(path));
    }

    /**
     * 将字符串/json对象转换为json对象, 同时将json对象中字符串格式的属性值转换为子json对象或数组
     * @param obj
     * @return
     */
    private Object toJson(Object obj) {
        if (obj == null) {
            return obj;
        }
        if (obj instanceof JSONObject) {
            return convertObjField((JSONObject)obj);
        }
        if (obj instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray)obj;
            for (int i=0; i<jsonArray.size(); i++) {
                jsonArray.set(i, toJson(jsonArray.get(i)));
            }
            return jsonArray;
        }
        if (!(obj instanceof String)) {
            return obj;
        }

        String objStr = obj.toString().trim();
        if (objStr.startsWith("{")) {
            JSONObject jsonObj = JSONObject.parseObject(objStr);
            return convertObjField(jsonObj);
        } else if (objStr.startsWith("[")) {
            JSONArray jsonArray = JSONArray.parseArray(objStr);
            for (int i=0; i<jsonArray.size(); i++) {
                jsonArray.set(i, toJson(jsonArray.get(i)));
            }
            return jsonArray;
        }
        return obj;
    }

    /**
     * 递归检查json对象中的属性值, 如果为字符串格式的对象或数组, 则将字符串转换为子json对象或数组
     * @param jsonObj
     * @return
     */
    private JSONObject convertObjField(JSONObject jsonObj) {
        Set<String> keys = jsonObj.keySet();
        for (String key : keys) {
            Object value = jsonObj.get(key);
            if (value == null) {
                continue;
            }

            String objStr = value.toString().trim();
            if (objStr.startsWith("{") || objStr.startsWith("[")) {
                jsonObj.put(key, toJson(value));
            }
        }
        return jsonObj;
    }
}
